import {
	createRouter,
	createWebHistory
} from 'vue-router'
import {
	showConfirmDialog
} from "vant";

const routes = [{
	path: '/',
	name: 'Home',
	component: () => import('../views/Home.vue'),
	meta: {
		title: '首页',
		requireAuth: true,
		isbottom: true
	}
},
{
	path: '/recommend',
	name: 'Recommend',
	component: () => import('../views/Recommend.vue'),
	meta: {
		isbottom: true,
		requireAuth: true,
	}
},

{
	path: '/personal',
	name: 'Personal',
	component: () => import('../views/Personal.vue'),
	meta: {
		requireAuth: false,
		isbottom: true
	}
},
{
	path: '/booking',
	name: 'Booking',
	component: () => import('../views/Booking.vue'),
	meta: {
		isbottom: false
	}
},
{
	path: '/order',
	name: 'Order',
	component: () => import('../views/Order.vue'),
	meta: {
		title: '我的订单',
		isbottom: false
	}
},
{
	path: '/settingscenter',
	name: 'SettingsCenter',
	component: () => import('../views/SettingsCenter.vue'),
	meta: {
		title: '个人信息',
		isbottom: false
	}
},
{
	path: '/login',
	name: 'Login',
	component: () => import('../views/Login.vue'),
	meta: {
		title: '登录',
		isbottom: false
	}
}, {
	path: '/register',
	name: 'Register',
	component: () => import('../views/Register.vue'),
	meta: {
		title: '注册',
		isbottom: false
	}
},
{
	path: '/driverRegistration',
	name: 'DriverRegistration',
	component: () => import('../views/DriverRegistration.vue'),
	meta: {
		title: '司机注册',
		isbottom: false
	}
},
{
	path: '/myorder',
	name: 'MyOrder',
	component: () => import('../views/MyOrder.vue'),
	meta: {
		title: '我的预约',
		isbottom: false
	}
},
{
	path: '/new-order',
	name: 'NewOrder',
	component: () => import('../views/NewOrder.vue'),
	meta: {
		title: '新建订单',
		isbottom: false
	}
},
{
	path: '/MemberCenter',
	name: 'MemberCenter',
	component: () => import('../views/MemberCenter.vue'),
	meta: {
		title: '会员中心',
		isbottom: false
	}
},
{
	path: '/usersettings',
	name: 'UserSettings',
	component: () => import('../views/UserSettings.vue'),
	meta: {
		title: '设置中心',
		isbottom: false
	}
}
]
//requireAuth是否需要放行路由不需要验证的，直接放行
const router = createRouter({
	history: createWebHistory(),
	routes
})
router.beforeEach((to, from, next) => {
	if (to.name === 'Login'||to.name === 'Register') { // 路由条状到login的，直接放行
		next(); // 路由继续往下跳转
		return;
	}

	if (to.meta.requireAuth) { // 路由不需要验证的，直接放行
		next();
		return;
	}


	const token = localStorage.getItem('token')
	if (!token) { // 如果token不存在的，则跳转登录login
		showConfirmDialog({
			message: "请先登录",
		}).then(() => {
			// 需要登录，则跳转到登录login，并传递参数(登录后跳转的路由)
			router.push({ name: "Login" });
		}).catch(() => { // 用户取消登录操作
			// 取消登录，跳转到首页
			router.push({ name: "Home" });
		});
		return;
	}
	console.log(`${from.name}跳转到${to.name},目的路由需要用户认证，Token也存在！`); // 控制台调试输出
	// 其余情况，则路由放行
	next(); //
});
router.afterEach(() => {
	window.scrollTo(0, 0); // 滚动到页面顶部
});
export default router